﻿using AutoMapper;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using AutoMapper.Configuration;

namespace NE.Utility
{
    /// <summary>
    /// AutoMapper扩展
    /// </summary>
    public static class AutoMapperExtensions
    {
        private static IMapper _mapper = null;

        private static readonly object _typeLock = new object();

        private static MapperConfigurationExpression _express = new MapperConfigurationExpression();
        /// <summary>
        ///     Map source object to destination object
        /// </summary>
        /// <typeparam name="TSource">Source</typeparam>
        /// <typeparam name="TDestination">Destination</typeparam>
        /// <param name="source">Source object</param>
        /// <param name="destination">Destination object</param>
        /// <returns>TDestination</returns>
        public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
        {
            return MapTo<TDestination>(source, destination);
        }

        /// <summary>
        ///     Map source object to destination object
        /// </summary>
        /// <typeparam name="TDestination">Destination</typeparam>
        /// <param name="source">Source</param>
        /// <returns>TDestination</returns>
        public static TDestination MapTo<TDestination>(this object source) where TDestination : new()
        {
            return MapTo(source, new TDestination());
        }

        /// <summary>
        ///     Map source object to destination object
        /// </summary>
        /// <typeparam name="TDestination">Destination type</typeparam>
        /// <param name="source">Source</param>
        /// <param name="destination">Destination</param>
        /// <returns>TDestination</returns>
        private static TDestination MapTo<TDestination>(object source, TDestination destination)
        {
            var sourceType = GetType(source);
            var destinationType = GetType(destination);
            CreateMapper(sourceType, destinationType);
            return (TDestination)_mapper.Map(source, destination, source.GetType(), typeof(TDestination));
        }

        /// <summary>
        ///     Map Source collections to target collections
        /// </summary>
        /// <typeparam name="TDestination">Destination</typeparam>
        /// <param name="source">Source</param>
        /// <returns>List<TDestination></returns>
        public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
        {
            return MapTo<List<TDestination>>(source);
        }

        /// <summary>
        /// Gets object type
        /// </summary>
        private static Type GetType(object obj)
        {
            if (obj == null) throw new ArgumentNullException("object is null");

            var type = obj.GetType();
            if (obj is IEnumerable == false)
                return type;
            if (type.IsArray)
                return type.GetElementType();
            var genericArgumentsTypes = type.GetTypeInfo().GetGenericArguments();
            if (genericArgumentsTypes == null || genericArgumentsTypes.Length == 0)
                throw new ArgumentException("Generic type parameter can not be empty for mapping.");
            return genericArgumentsTypes[0];
        }

        /// <summary>
        ///     Create Mapping Configuration
        /// </summary>
        /// <param name="sourceType">Source</param>
        /// <param name="destinationType">Destination</param>
        /// <returns>TypeMap</returns>
        private static void CreateMapper(Type source, Type dest)
        {
            var typeMapper = _mapper?.ConfigurationProvider?.FindTypeMapFor(source, dest);
            if (typeMapper != null) return;
            lock (_typeLock)
            {
                typeMapper = _mapper?.ConfigurationProvider?.FindTypeMapFor(source, dest);
                if (typeMapper != null) return;

                _express.CreateMap(source, dest);
                _mapper = new MapperConfiguration(_express).CreateMapper();
            }
        }

        public static void Init(params Action<IMapperConfigurationExpression>[] inits)
        {
            inits?.ToList().ForEach(i => i.Invoke(_express));
            _mapper = new MapperConfiguration(_express).CreateMapper();
        }
    }
}